<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>创建您的账户，开始使用AI平台</p>
      </div>
      
      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="registerForm.username"
            type="text"
            placeholder="请输入用户名"
            :class="['form-input', { 'error': errors.username }]"
            @blur="validateField('username')"
          />
          <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
        </div>
        
        <div class="form-group">
          <label for="nickName">昵称</label>
          <input
            id="nickName"
            v-model="registerForm.nickName"
            type="text"
            placeholder="请输入昵称"
            :class="['form-input', { 'error': errors.nickName }]"
            @blur="validateField('nickName')"
          />
          <span v-if="errors.nickName" class="error-message">{{ errors.nickName }}</span>
        </div>
        
        <div class="form-group">
          <label for="email">邮箱</label>
          <input
            id="email"
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            :class="['form-input', { 'error': errors.email }]"
            @blur="validateField('email')"
          />
          <span v-if="errors.email" class="error-message">{{ errors.email }}</span>
        </div>
        
        <div class="form-group">
          <label for="phonenumber">手机号</label>
          <input
            id="phonenumber"
            v-model="registerForm.phonenumber"
            type="tel"
            placeholder="请输入手机号"
            :class="['form-input', { 'error': errors.phonenumber }]"
            @blur="validateField('phonenumber')"
          />
          <span v-if="errors.phonenumber" class="error-message">{{ errors.phonenumber }}</span>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <div class="password-input-wrapper">
            <input
              id="password"
              v-model="registerForm.password"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码"
              :class="['form-input', { 'error': errors.password }]"
              @blur="validateField('password')"
            />
            <button
              type="button"
              class="password-toggle"
              @click="showPassword = !showPassword"
            >
              <svg v-if="showPassword" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                <line x1="1" y1="1" x2="23" y2="23"></line>
              </svg>
              <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                <circle cx="12" cy="12" r="3"></circle>
              </svg>
            </button>
          </div>
          <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
        </div>
        
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <div class="password-input-wrapper">
            <input
              id="confirmPassword"
              v-model="registerForm.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请再次输入密码"
              :class="['form-input', { 'error': errors.confirmPassword }]"
              @blur="validateField('confirmPassword')"
            />
            <button
              type="button"
              class="password-toggle"
              @click="showConfirmPassword = !showConfirmPassword"
            >
              <svg v-if="showConfirmPassword" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                <line x1="1" y1="1" x2="23" y2="23"></line>
              </svg>
              <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                <circle cx="12" cy="12" r="3"></circle>
              </svg>
            </button>
          </div>
          <span v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</span>
        </div>
        
        <div class="form-group" v-if="captchaEnabled">
          <label for="code">验证码</label>
          <div class="captcha-input-wrapper">
            <input
              id="code"
              v-model="registerForm.code"
              type="text"
              placeholder="请输入验证码"
              :class="['form-input', 'captcha-input', { 'error': errors.code }]"
              @blur="validateField('code')"
              maxlength="4"
            />
            <div class="captcha-image-wrapper">
              <img 
                :src="codeUrl" 
                @click="getCode" 
                class="captcha-image"
                alt="验证码"
                title="点击刷新验证码"
              />
            </div>
          </div>
          <span v-if="errors.code" class="error-message">{{ errors.code }}</span>
        </div>
        
        <div class="form-group">
          <label class="checkbox-label">
            <input
              v-model="registerForm.agreement"
              type="checkbox"
              class="checkbox-input"
            />
            <span class="checkbox-text">
              我已阅读并同意
              <a href="#" class="link">《用户协议》</a>
              和
              <a href="#" class="link">《隐私政策》</a>
            </span>
          </label>
          <span v-if="errors.agreement" class="error-message">{{ errors.agreement }}</span>
        </div>
        
        <button
          type="submit"
          class="register-btn"
          :disabled="loading || !isFormValid"
        >
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '注册中...' : '立即注册' }}
        </button>
      </form>
      
      <div class="register-footer">
        <p>
          已有账户？
          <router-link to="/login" class="link">立即登录</router-link>
        </p>
        <p>
          <router-link to="/" class="link">返回首页</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getCodeImg, register as registerUser } from '@/api/agriculture/xctl/auth'

const router = useRouter()

// 表单数据
const registerForm = ref({
  username: '',
  nickName: '',
  email: '',
  phonenumber: '',
  password: '',
  confirmPassword: '',
  code: '',
  uuid: '',
  agreement: false
})

// 表单验证错误
const errors = ref({})

// 状态管理
const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const codeUrl = ref('')
const captchaEnabled = ref(true)

// 表单验证规则
const validateField = (field) => {
  const value = registerForm.value[field]
  
  switch (field) {
    case 'username':
      if (!value) {
        errors.value.username = '用户名不能为空'
      } else if (value.length < 3 || value.length > 20) {
        errors.value.username = '用户名长度应在3-20个字符之间'
      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
        errors.value.username = '用户名只能包含字母、数字和下划线'
      } else {
        delete errors.value.username
      }
      break
      
    case 'nickName':
      if (!value) {
        errors.value.nickName = '昵称不能为空'
      } else if (value.length < 2 || value.length > 20) {
        errors.value.nickName = '昵称长度应在2-20个字符之间'
      } else {
        delete errors.value.nickName
      }
      break
      
    case 'email':
      if (!value) {
        errors.value.email = '邮箱不能为空'
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        errors.value.email = '请输入有效的邮箱地址'
      } else {
        delete errors.value.email
      }
      break
      
    case 'phonenumber':
      if (!value) {
        errors.value.phonenumber = '手机号不能为空'
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        errors.value.phonenumber = '请输入有效的手机号'
      } else {
        delete errors.value.phonenumber
      }
      break
      
    case 'password':
      if (!value) {
        errors.value.password = '密码不能为空'
      } else if (value.length < 6 || value.length > 20) {
        errors.value.password = '密码长度应在6-20个字符之间'
      } else if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
        errors.value.password = '密码必须包含字母和数字'
      } else {
        delete errors.value.password
      }
      break
      
    case 'confirmPassword':
      if (!value) {
        errors.value.confirmPassword = '确认密码不能为空'
      } else if (value !== registerForm.value.password) {
        errors.value.confirmPassword = '两次输入的密码不一致'
      } else {
        delete errors.value.confirmPassword
      }
      break
      
    case 'agreement':
      if (!registerForm.value.agreement) {
        errors.value.agreement = '请阅读并同意用户协议和隐私政策'
      } else {
        delete errors.value.agreement
      }
      break
      
    case 'code':
      if (!value) {
        errors.value.code = '验证码不能为空'
      }  else {
        delete errors.value.code
      }
      break
  }
}

// 验证所有字段
const validateAllFields = () => {
  Object.keys(registerForm.value).forEach(field => {
    validateField(field)
  })
}

// 表单是否有效
const isFormValid = computed(() => {
  return Object.keys(errors.value).length === 0 &&
         registerForm.value.username &&
         registerForm.value.nickName &&
         registerForm.value.email &&
         registerForm.value.phonenumber &&
         registerForm.value.password &&
         registerForm.value.confirmPassword &&
         registerForm.value.code &&
         registerForm.value.agreement
})

// 获取验证码
const getCode = async () => {
  try {
    const response = await getCodeImg()
    captchaEnabled.value = response.captchaEnabled === undefined ? true : response.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + response.img
      registerForm.value.uuid = response.uuid
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 处理注册
const handleRegister = async () => {
  validateAllFields()
  
  if (!isFormValid.value) {
    return
  }
  
  loading.value = true
  
  try {
    const { confirmPassword, agreement, ...registerData } = registerForm.value
    
    const response = await registerUser(registerData)
    
    if (response.code === 200) {
      // 注册成功
      alert('注册成功！请登录')
      router.push('/login')
    } else {
      alert(response.msg || '注册失败，请重试')
      // 注册失败时刷新验证码
      if (captchaEnabled.value) {
        getCode()
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    alert('注册失败，请检查网络连接后重试')
    // 注册失败时刷新验证码
    if (captchaEnabled.value) {
      getCode()
    }
  } finally {
    loading.value = false
  }
}

// 页面加载时获取验证码
getCode()
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 20px 20px 40px 20px;
  overflow-y: auto;
  /* 美化滚动条 */
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

/* Webkit浏览器滚动条样式 */
.register-container::-webkit-scrollbar {
  width: 6px;
}

.register-container::-webkit-scrollbar-track {
  background: transparent;
}

.register-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.register-container::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

.register-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  padding: 32px;
  width: 100%;
  max-width: 420px;
  margin: 20px 0 40px 0;
  max-height: calc(100vh - 80px);
  overflow-y: auto;
  /* 美化卡片内滚动条 */
  scrollbar-width: thin;
  scrollbar-color: rgba(59, 130, 246, 0.3) transparent;
}

/* 卡片内滚动条样式 */
.register-card::-webkit-scrollbar {
  width: 6px;
}

.register-card::-webkit-scrollbar-track {
  background: transparent;
}

.register-card::-webkit-scrollbar-thumb {
  background: rgba(59, 130, 246, 0.3);
  border-radius: 3px;
}

.register-card::-webkit-scrollbar-thumb:hover {
  background: rgba(59, 130, 246, 0.5);
}

.register-header {
  text-align: center;
  margin-bottom: 24px;
}

.register-header h2 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 6px;
}

.register-header p {
  color: #6b7280;
  font-size: 16px;
  margin: 0;
}

.register-form {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 14px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s ease, box-shadow 0.2s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-input.error {
  border-color: #ef4444;
}

.password-input-wrapper {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.2s ease;
}

.password-toggle:hover {
  color: #374151;
}

.captcha-input-wrapper {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
  min-width: 0;
}

.captcha-image-wrapper {
  flex-shrink: 0;
}

.captcha-image {
  width: 100px;
  height: 38px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: border-color 0.3s ease;
  object-fit: cover;
}

.captcha-image:hover {
  border-color: #3b82f6;
}

.checkbox-label {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
}

.checkbox-input {
  margin: 0;
  margin-top: 2px;
}

.checkbox-text {
  color: #6b7280;
  line-height: 1.5;
}

.error-message {
  display: block;
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
}

.register-btn {
  width: 100%;
  background: #3b82f6;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.register-btn:hover:not(:disabled) {
  background: #2563eb;
}

.register-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.register-footer {
  text-align: center;
  color: #6b7280;
  font-size: 14px;
}

.register-footer p {
  margin: 8px 0;
}

.link {
  color: #3b82f6;
  text-decoration: none;
  font-weight: 500;
}

.link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .register-container {
    padding: 12px 12px 30px 12px;
    align-items: flex-start;
  }
  
  .register-card {
    padding: 20px;
    margin: 10px 0 30px 0;
    max-height: calc(100vh - 60px);
    border-radius: 12px;
  }
  
  .register-header {
    margin-bottom: 20px;
  }
  
  .register-header h2 {
    font-size: 20px;
  }
  
  .register-header p {
    font-size: 14px;
  }
  
  .form-group {
    margin-bottom: 14px;
  }
  
  .form-input {
    padding: 8px 12px;
    font-size: 14px;
  }
  
  .register-btn {
    padding: 10px 16px;
    font-size: 14px;
  }
}
</style>